import loadjs from "loadjs";
import { Bubble } from 'weaver-mobile';
import * as Common from './common';
import {saveCAAuthResult} from "../apis/secondAuth";
import * as authTypes from "../constants/secondAuthType";
import * as EmSDK from "./emSDK";

const getLabel = Common.getLabel;

/**
 * 格式化日期的工具类方法
 * @param fmt
 */
const formatDate4QysUkey = (date, fmt) => {
    const that = date;
    var o = {
        "M+": that.getMonth() + 1,                 //月份
        "d+": that.getDate(),                    //日
        "h+": that.getHours(),                   //小时
        "m+": that.getMinutes(),                 //分
        "s+": that.getSeconds(),                 //秒
        "q+": Math.floor((that.getMonth() + 3) / 3), //季度
        "S": that.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (that.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }

    return fmt;
}


export const QYSUKeyUtil = (() => {
    /**
     * 契约锁ukey的js库
     */
    const resourceFiles = [
        "/workflow/qyskey/HTML.SDK.js"
    ];

    /**
     * 契约锁html签章实例
     */
    let qysHtmlInstance = null;
    /**
     *  异步加载契约锁js sdk资源
     */
    const ayncLoadResource = (callback, para) => {
        const callbackFn = () => {
            callback && callback(para);
        }
        loadjs.isDefined('qysHtml4Ukey') ? loadjs.ready('qysHtml4Ukey', callbackFn) : loadjs(resourceFiles, 'qysHtml4Ukey', callbackFn);
    };
    const cancelCb = store =>{
        if(store && store.setDialogData){
            store.setDialogData({clearButten:false});
        }
        EmSDK.controlBottomBtn('/req');
    }
    const confirmCb = store =>{
        if(store && store.setDialogData){
            store.setDialogData({clearButten:false});
        }
        EmSDK.controlBottomBtn('/req');
    }
    const initCb = store =>{
        if(store){
            store.setDialogData({clearButten:true});
        }
        EmSDK.resetBottomBtn();
    }
    /**
     * 异步加载契约锁js sdk资源，然后弹出认证窗口
     */
    const showSignWin0 = store => {

        const qysHtmlParams =  {
            cancelCb:function(){
                cancelCb(store);
            }
        };
        if (qysHtmlInstance == null) {
            qysHtmlInstance = new window.QysHtml(qysHtmlParams);
        }

        const {authKey = "", sourcestr = "", secondAuthType, protectType, isProtectDialog, callbackFunc, callbackParam} = store;

        /**
         * 签署成功的回调方法
         */
        const completeSign = result => {
            result = JSON.parse(result);
            const {p7, timeStamp, apperance} = result;

            /**
             *************** 做流程的提交操作********************
             */
            const data = {
                plaintext: sourcestr,
                p7
            };

            //调用js SDK接口获取证书等信息
            const verifyResult = qysHtmlInstance.verify(JSON.stringify(data));
            const {result: vresult = {},code = 0,message = ""} = verifyResult;

            if(code != 0){
                cancelCb(store);
                Bubble.error((!!message)?message:getLabel(389490, "认证失败"));
                return;
            }
            const {cert = {}} = vresult;
            const {validity = {}} = cert;

            //参数按照顺序，分别是证书编号，所有者，证书颁发机构
            const {sn: seriNo, companyName:corpName, organizationName: tenantName, certIssuer: caType} = cert;
            //证书有效期
            const dateFmt = "yyyy-MM-dd hh:mm:ss";
            const {notBefore, notAfter} = validity;
            const startTime = formatDate4QysUkey(notBefore, dateFmt);
            const endTime = formatDate4QysUkey(notAfter, dateFmt);
            const date = new Date(timeStamp);
            const signTime = formatDate4QysUkey(date, dateFmt);

            //选择的印章信息(base64格式的图片信息）
            const {sealImg: qysSealImg,position} = apperance;
            const {width:qyswidth = 0,height:qysheight = 0} = position;
            const qysCertDetails = {seriNo, tenantName, caType, startTime, endTime, signTime,qyswidth,qysheight,corpName};

            const checkSuccess = () => {
                if (isProtectDialog == 1) {
                    store.setDialogResult({isProtectSuccess: 1});  //数据保护成功
                } else if (isProtectDialog == 10) {     //CA认证 + CA数据保护 或者 契约锁认证 + 契约锁数据保护
                    store.setDialogResult({isProtectSuccess: 1});  //数据保护成功
                    store.setDialogResult({isAuthSuccess: 1});  //二次验证成功
                } else {        //二次验证：CA或者契约锁验证
                    store.setDialogResult({isAuthSuccess: 1});  //二次验证成功
                }

                //契约锁验证或者数据保护，保存印章信息
                if (secondAuthType == authTypes.QYS || (isProtectDialog == 1 && protectType == authTypes.QYS)) {
                    const {params} = store;
                    store.setAuthResult({
                        ...params,
                        qysSealId: 0,
                        qysSealImg,
                        qysCertDetails: JSON.stringify(qysCertDetails)
                    });
                }

                confirmCb(store);
                if (callbackFunc && typeof callbackFunc == "function") {
                    callbackFunc.call({}, callbackParam);    //调用提交流程的方法
                }
            }

            /**
             ***************************** 将验证的结果存入数据库*******************
             */
            if (isProtectDialog == 1 || isProtectDialog == 10) {//如果是数据保护，则先保存加密数据，否则直接提交流程
                saveCAAuthResult({authKey, signValue: p7}).then(response => {
                    let success = response.success;
                    if (success == 1) {     //保存成功
                        checkSuccess();     //提交流程
                    } else {
                        cancelCb(store);
                        Bubble.error(getLabel(389490, "认证失败"));
                    }
                });
            }else{
                checkSuccess();     //提交流程
            }
        }

        const para = {
            plaintext: sourcestr,
            position: {
                x: '50%',
                y: '50%',
            }
        };
        initCb(store);
        qysHtmlInstance.selectSeal(JSON.stringify(para), completeSign);
    }


    return {
        showSignWin: store => {
            ayncLoadResource(showSignWin0, store);
        }
    };
})()